Red-Black Trees
Properties of red-black trees
- A red-black tree is a binary search tree with one extra bit of storage per node: its color, which can be either RED or BLACK.
- Each node of the tree now contains the attributes color, key, left, right, and p
- A red-black tree is a binary tree that satisfies the following
red-black properties:
- Every node is either red or black
- The root is black
- Every leaf (NIL) is black
- If a node is red, then both its children are black
- For each node, all simple paths from the node to descendant leaves contain the same number of black nodes
- We call the number of black nodes on any simple
path from, but not including, a node x down to a leaf the
black-height of the node, denoted
- Lemma 13.1:A red-black tree with
internal nodes has height at most
Rotations
- We change the pointer structure through rotation, which is a local operation in a search tree that preserves the binary-search-tree property
- the two kinds of rotations: left rotations and right rotations.
1 | LEFT-ROTATE(T,x) |
- The code for RIGHT-ROTATE is symmetric. Both LEFT-ROTATE and
RIGHT-ROTATE run in
time.
Insertion
1 | RB-INSERT(T,z) |
1 | RB-INSERT-FIXUP(T,z) |
- Moreover, it never performs more than two rotations, since the while loop terminates if case 2 or case 3 is executed.
- Thus, the only properties that might be violated are property 2, which requires the root to be black, and property 4, which says that a red node cannot have a red child
- Case 1: z’s uncle y is red;
- Case 2: z’s uncle y is black and z is a right child
- Case 3: z’s uncle y is black and z is a left child
Deletion
1 | TRANSPLANT(T,u,v) |
- The procedure RB-TRANSPLANT differs from TRANSPLANT in two ways.
- First, line 1 references the sentinel T.nil instead of NIL.
- Second, the assignment to v.p in line 6 occurs unconditionally
1 | RB-DELETE(T,z) |
1 | RB-DELETE-FIXUP(T,x) |
- Case 1: x’s sibling w is red
- Case 2: x’s sibling w is black, and both of w’s children are black
- Case 3: x’s sibling w is black, w’s left child is red, and w’s right child is black
- Case 4: x’s sibling w is black, and w’s right child is red
推荐阅读